package com.heaven.customerServer.customerController;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import com.heaven.constant.SaTokenConstants;
import com.heaven.customerServer.customerController.vo.login.LoginRes;
import com.heaven.exception.BizCodeEnum;
import com.heaven.service.LoginService;
import com.heaven.service.minio.MinIoService;
import com.heaven.utils.R;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("heaven-server/login")
public class LoginController {

    @Resource
    private LoginService loginService;
    @Resource
    private MinIoService minIoService;

    @RequestMapping("isLogin")
    public R isLogin() {
        return R.okData(StpUtil.isLogin());
    }

    @RequestMapping("loginWithPwd")
    public R loginWithPwd(@RequestParam("username") String username, @RequestParam("pwd") String password) {
        LoginRes ans = loginService.loginWithPwd(username, password);
        if(ans.getLoginStatus()){
            return R.okData(ans);
        }else {
            return R.error(BizCodeEnum.USER_LOGIN_FAIL);
        }
    }

    @RequestMapping("logout")
    public R logout() {
        StpUtil.logout();
        return R.okData(null);
    }

    @GetMapping("getSession")
    public R getSession(){
        SaSession session = StpUtil.getSession();
        LoginRes.UserSession userSession = (LoginRes.UserSession) session.get(SaTokenConstants.USER_SESSION_KEY);
        userSession.setHeader(minIoService.getLink(userSession.getHeader()));
        return R.okData(session);
    }

    /**
     * 获取Session的用户基本信息
     */
    public LoginRes.UserSession getUserSession() {
        LoginRes.UserSession ans;
        try{
            ans = (LoginRes.UserSession) StpUtil.getSession().get(SaTokenConstants.USER_SESSION_KEY);
        }catch (NotLoginException e){
            return null;
        }
        return ans;
    }



}
